﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;

namespace ZGSharp
{
	public abstract class Model
	{
		protected abstract Tensor forward(Tensor input);

		public Tensor Run(Tensor input)
		{
			this.forward(null); //清空图节点
			return this.forward(input);
		}

		public void SaveModel(string filePath)
		{
			this.forward(null); //清空图节点
			Tensor input = new Tensor();
			Tensor output = this.forward(input);
			List<string> save_msg = new List<string>();
			output.tensor_id = 0;
			int layer_count = 1;
			output.SaveBackward(output, save_msg, ref layer_count);
			StringBuilder sb_save = new StringBuilder();
			foreach (string line in save_msg)
			{
				sb_save.Append(line);
				sb_save.Append(";\n");
			}
			File.WriteAllText(filePath, sb_save.ToString());
		}

		public void ModelRestore(string filePath) 
		{
			if (File.Exists(filePath))
            {
				this.forward(null); //清空图节点
				Tensor input = new Tensor();
				Tensor output = this.forward(input);

				string file_info = File.ReadAllText(filePath);
				List<string> save_msg = new List<string>();
				save_msg.AddRange(file_info.Split(';'));
				output.tensor_id = 0;
				int layer_count = 1;
				output.StoreBackward(output, save_msg, ref layer_count);
			}
		}
	}
}
